package com.songxh.filter;

import com.alibaba.fastjson.JSON;
import com.songxh.common.BaseContext;
import com.songxh.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author songxh
 * @create 2022-04-22-16:59
 */
@WebFilter(filterName = "LoginCheckFilter")
@Slf4j
public class LoginCheckFilter implements Filter {

    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取URI，并将不需要过滤的路径写出
        String uri = request.getRequestURI();

        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

        //判断本次请求是否需要处理
        boolean check = check(urls, uri);
        //如果不需要处理 直接放行
        if (check){
            filterChain.doFilter(request, response);
            return;
        }

        //判断登录状态，若已经登录，则直接放行
        if(request.getSession().getAttribute("employee")!=null){

            //将session域中的用户id传进线程当中
            long empId = (long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);
            return;
        }

        //判断前台登录状态，若已经登录，则直接放行
        //即判断session当中是否有key=”user“的数据
        if(request.getSession().getAttribute("user")!=null){

            //将session域中的用户id传进线程当中
            long userId = (long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }

        //如果未登录则显示未登录的结果，通过输出流的方式向客户端响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        log.info("拦截到请求：{}", request.getRequestURI());
        return;
    }

    /**
     *路径匹配，判断该路径是否放行
     * @param urls   不需要过滤的路径
     * @param uri
     * @return
     */
    public boolean check(String[] urls,String uri){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if (match){
                return true;
            }
        }
        return false;
    }

}
